<template>
    <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
            <el-input v-model="form.pwd"></el-input>
        </el-form-item>
        <!-- <el-form-item label="再次输入密码" prop="againPwd" auto-complete="off">
            <el-input v-model="form.againPwd"></el-input>
        </el-form-item> -->
        <el-form-item>
            <el-button type="primary" @click="onSubmit">登录</el-button>
        </el-form-item>
    </el-form>
</template>
<script>
 export default {
    data() {
        var validatePass = (rule,value,callback) => {
            if(value === ''){
                callback(new Error('请再次输入密码'))
            }else if(value !== this.form.pwd){
                callback(new Error('两次输入密码不一致!'))
            }else{
                callback();
            }
        }
      return {
        form: {
            username: '',
            pwd:'',
            againPwd:''
        },
        rules:{
            username:[
                {required:true,message:'请输入用户名',trigger:'blur'},
                {min:3,max:5,message:'长度在3到5之间',trigger:'blur'}
            ],
            pwd:[
                {required:true,message:'请输入密码',trigger:'blur'},
                {min:3,max:5,message:'长度在3到5之间',trigger:'blur'}
            ],
            againPwd:[
                {required:true,message:'请再次输入密码',trigger:'blur'},
                {
                    validator:validatePass,trigger:true
                }
            ]
        }
      }
    },
    methods: {
      onSubmit() {
          this.$refs.form.validate((valid) => {
                if(valid){
                    console.log("提交");
                    let that = this;
                    this.$http.post('/api/login',this.form).then((res) => {
                        if(res.data.code === 1){
                            this.$message({
                                message: '恭喜你,登录成功',
                                type: 'success',
                                onClose(){
                                    localStorage.setItem('uid',that.form.username);
                                    that.$router.push({path:'/home'});
                                }
                            });
                        }
                    }).catch((errpr) => {
                        console.warn(error)
                    })
                }else{
                    console.log("校验失败");
                    return false
                }
          })
       
      }
    }
  }
</script>
